<template>
  <el-button type="primary" @click="resetMap" :loading="loading">重置</el-button>
  <div ref="mapChart" style="width: 100%; height: 400px"></div>
</template>

<script setup>
import axios from 'axios'
import { ref, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { queryPatrolAlarmLocationByOrgId } from '@/api/monitorApi'
import { useRoute } from 'vue-router'
import { useBaseParamStore } from '@/stores/baseParams'

const baseParamStore = useBaseParamStore()
const route = useRoute()
const mapChart = ref(null)
const initMyChart = ref()
const initAdCode = ref(100000) // 默认地图的编码
const currentMapName = ref('中国') // 默认地图的名称
const adCodeMap = ref([]) // 当前选中省市区的所有名称和编码
const loading = ref(false)
const mapLevel = ref(0) // 0 表示中国，1 表示省份，2 表示城市

onMounted(() => {
  getPatrolAlarmLocationByOrgId()
  initMyChart.value = echarts.init(mapChart.value)
})

// 本月告警单、巡查任务统计地图
const loactionInfo = ref()
const getPatrolAlarmLocationByOrgId = async (adCode = 100000) => {
  try {
    const res = await queryPatrolAlarmLocationByOrgId({
      orgId: route.query.orgId,
      startDate: baseParamStore.baseParam?.pickTime[0],
      endDate: baseParamStore.baseParam?.pickTime[1],
      city: currentMapName.value == '中国' ? '温氏' : '温氏'
    })
    if (res && res.data) {
      loactionInfo.value = res.data
      getMapData(adCode)
    }
  } catch (error) {
    console.error('获取本月告警单、巡查任务统计地图信息失败:', error)
  }
}

// 初始化
const initChart = (mapName, mapData, dotData = []) => {
  dotData = dotData.map((item) => {
    return [item.longitude, item.latitude, 300]
  })
  console.log('dotData', dotData)
  echarts.registerMap(mapName, mapData)
  var option
  option = {
    visualMap: {
      // 热力图颜色显示
      // default: 'piecewise ',
      default: 5,
      calculable: true,
      textStyle: {
        color: '#fef420'
      },
      inRange: {
        color: ['#379fdf', '#df383e']
      }
    },
    geo: {
      map: mapName,
      zoom: '1.2', // 当前视角的缩放比例
      roam: false, // 可以通过鼠标滚轮放大缩小地图
      center: undefined // 中心点偏移量
    },
    series: [
      {
        type: 'map',
        map: mapName, // 注册地图的名称
        zoom: '1.2', // 当前视角的缩放比例
        center: undefined, // 中心点偏移量
        label: {
          show: true // 是否显示省份名字
        },
        data: [],
        roam: false, // 是否开启缩放和平移
        itemStyle: {
          borderColor: '#F59A23',
          borderType: 'dashed'
        },
        emphasis: {
          areaColor: '#184cff',
          shadowOffsetX: 0,
          shadowOffsetY: 0,
          shadowBlur: 5,
          borderWidth: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      },
      {
        // 散点分布
        roam: true,
        type: 'heatmap',
        coordinateSystem: 'geo',
        data: dotData,
        blurSize: 20,
        symbolSize: 20,
        symbol: 'arrow',
        minOpacity: 0.1,
        maxOpacity: 1
      }
    ]
  }

  console.log('option', option)
  option && initMyChart.value.setOption(option)

  // 省份下钻点击事件
  initMyChart.value.on('click', (params) => {
    console.log(params)
    const adCode = adCodeMap.value.find((item) => item.name == params.name).dcode
    console.log('adCode', adCode)
    // 判断是否可以继续下钻
    if (mapLevel.value >= 1) {
      console.log('已达到最大下钻层级')
      return
    }
    if (adCode) {
      currentMapName.value = params.name
      getPatrolAlarmLocationByOrgId(adCode)
      mapLevel.value += 1 // 下钻层级递增
    }
  })
}

// 获取地图数据
const getMapData = (map) => {
  axios
    .get(`https://geo.datav.aliyun.com/areas_v3/bound/${map}_full.json`)
    .then((res) => {
      if (res.status == '200') {
        loading.value = false
        initChart(currentMapName.value, res.data, loactionInfo.value)
        // 获取当前选中的省市区的所有名称和编码
        adCodeMap.value = []
        for (let i = 0; i < res.data.features.length; i++) {
          adCodeMap.value.push({
            name: res.data.features[i].properties.name,
            dcode: res.data.features[i].properties.adcode
          })
        }
      }
    })
    .catch((err) => {
      console.log(err)
    })
}

const resetMap = () => {
  loading.value = true
  initAdCode.value = 100000
  currentMapName.value = '中国'
  mapLevel.value = 0 // 下钻层级重置
  getMapData(initAdCode.value)
  getPatrolAlarmLocationByOrgId()
}
</script>
